package com.coocaa.cirrus.common.base.util;

import lombok.experimental.UtilityClass;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author bijiahao
 * @date : 2025/9/18 09:48
 * @description
 */
@UtilityClass
public class InstanceUtil {
    public static final <k, v> HashMap<k, v> newHashMap() {
        return new HashMap<>();
    }
    public static final <k, v> HashMap<k, v> newHashMap(int initSize) {
        return new HashMap<>(initSize);
    }


    public static final <E> ArrayList<E> newArrayList() {
        return new ArrayList<>();
    }

    public static final <E> ArrayList<E> newArrayList(int initSize) {
        return new ArrayList<>(initSize);
    }


    public static Map<String, String> obj2Map(Object obj) {
        Map<String, String> params = InstanceUtil.newHashMap();
        try {
            Field[] fields;
            Class<?> aClass = obj.getClass();
            for (; aClass != Object.class; aClass = aClass.getSuperclass()) {
                fields = aClass.getDeclaredFields();
                handleObj2Map(obj, fields, params);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return params;
    }

    private static void handleObj2Map(Object obj, Field[] fields, Map<String, String> params) throws IllegalAccessException {
        for (Field field : fields) {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                field.setAccessible(true);
                return null;
            });
            if (field.get(obj) instanceof String) {
                if (StringUtils.isNotBlank(field.get(obj).toString())) {
                    params.put(field.getName(), ((String) field.get(obj)).intern());
                }
            } else if (field.get(obj) instanceof Date) {
                if (field.get(obj) != null) {
                    String date = DateUtil.toLongString((Date) field.get(obj));
                    params.put(field.getName(), date);
                }
            } else {
                if (field.get(obj) != null) {
                    params.put(field.getName(), field.get(obj).toString());
                }
            }
        }
    }
}
